package com.thingple.rodbell.packet;

import android.util.Log;

import com.thingple.rodbell.PacketProcessor;
import com.thingple.rodbell.cmd.HandleState;
import com.thingple.rodbell.model.PacketTagInfo;


public class PacketProcessorImpl extends AbstractPacketProcessor implements Runnable, PacketProcessor {

    private static final String TAG = PacketProcessorImpl.class.getName();

    public PacketProcessorImpl() {
        init();
    }

    private void init() {
        reset();
    }

    public void reset() {
        q.clear();
        buf.clear();
        state = HandleState.Start;
    }

    @Override
    public void run() {

        Log.d(TAG, "Packet Processor 线程开始");
        while (work) {
            process(); // 不间断执行
            idle();
        }
        Log.d(TAG, "Packet Processor 线程结束");
    }

    private void idle() {
        if (q.isEmpty()) { // 如果没数据,就等待一会
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onState(final int state) {
        if (carryStateListener == null) {
            return;
        }
        carryStateListener.onStateChange(state);
    }

    @Override
    protected void onTag(final PacketTagInfo tag) {

        if (debug) {
            Log.d(TAG, "tag:" + tag.epc + "[" + tag.antId + "]");
        }
        if (tagListener == null) {
            return;
        }
        tagListener.onTag(tag);
    }

    @Override
    protected void onInventoryStatus(final int state) {
//        if (listener == null) {
//            return;
//        }
//        listener.onInventoryStateChange(state);
    }

}
